const express = require('express')
const router = express.Router()
const moment = require('moment')
const AccountModel = require('../../models/AccountModel')
let checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware')

// 添加首页路由规则
router.get('/', (req, res) => {
  res.redirect('/account')
})

router.get('/account', checkLoginMiddleware, (req, res, next) => {
  // let accounts = db.get('accounts').value()
  AccountModel.find()
    .sort({ time: -1 })
    .exec((err, data) => {
      if (err) {
        res.status(500).send('读取失败')
        return
      }
      console.log(data)
      res.render('account/list', { accounts: data, moment })
    })
})

router.get('/account/create', checkLoginMiddleware, (req, res, next) => {
  res.render('account/create')
})

router.post('/account', checkLoginMiddleware, (req, res, next) => {
  AccountModel.create(
    {
      ...req.body,
      time: moment(req.body.time).toDate()
    },
    (err, data) => {
      if (err) {
        res.status(500).send('插入失败')
        return
      }
      // 成功提醒
      res.render('result/success', { msg: '添加成功,哈哈', url: '/account' })
    }
  )
})

router.get('/account/:id', checkLoginMiddleware, (req, res) => {
  // 获取 params 的 id 参数
  let id = req.params.id
  // 删除
  // db.get('accounts').remove({ id }).write()
  AccountModel.deleteOne({ _id: id }, (err, data) => {
    if (err) {
      res.status(500).send('删除失败')
      return
    }
    res.render('result/success', { msg: '账单删除成功', url: '/account' })
  })
  // 提示
  // res.send('删除成功')
})

module.exports = router
